﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    internal static class Program
    {
        /// <summary>
        /// 焦点切换指定的窗口，并将其带到前台
        /// </summary>
        /// <param name="hWnd"></param>
        /// <param name="fAltTab"></param>
        [DllImport("user32.dll")]
        public static extern void SwitchToThisWindow(IntPtr hWnd, bool fAltTab);

        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            //Process current = Process.GetCurrentProcess();
            //Process[] processes = Process.GetProcessesByName(current.ProcessName);

            //foreach (Process process in processes)
            //{
            //    if (process.Id != current.Id)
            //    { //根据进程ID排除当前进程
            //        MessageBox.Show("系统已启动");
            //        IntPtr handle = process.MainWindowHandle;
            //        //将原进程显示在最前
            //        SwitchToThisWindow(handle, true);
            //        current.Close();
            //        return;
            //    }
            //}
            //bool createdNew;
            //Mutex mutex = new Mutex(true, "ED4D323242424324242ERS", out createdNew); // 使用唯一的GUID作为互斥锁名称

            ////
            //if (!createdNew)
            //{
            //    var current = Process.GetCurrentProcess();
            //    var processes = Process.GetProcessesByName(current.ProcessName);

            //    var process = processes.FirstOrDefault(x => x.Id == current.Id);
            //    if (process != null)
            //    {
            //        MessageBox.Show("系统已启动");
            //        IntPtr handle = process.MainWindowHandle;
            //        SwitchToThisWindow(handle, true);
            //    }
            //    current.Close();
            //    return;
            //}
            var instance = UniqueProcess.RunningInstance();
            if (instance != null)
            {
                UniqueProcess.HandleRunningInstance(instance);

                return;
            }

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }
    }
}
